package com.hc.utils;

import com.hc.domain.Menu;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
public class MenuTreeUtil {

    public static List<Menu>  makeListToTree(List<Menu> menus){

        List<Menu> uniqueMenus = menus.stream().collect(Collectors.toMap(Menu::getId, e -> e, (e1, e2) -> e1))
                .values()
                .stream()
                .collect(Collectors.toList());

        List<Menu> parentList = uniqueMenus.stream().filter(e -> e.getParentId() == 0).collect(Collectors.toList());

        for (Menu parent : parentList) {
            List<Menu> menusTrees = toTree(parent.getId(), uniqueMenus);
            parent.setChildren(menusTrees);
        }

        return parentList;
    }

    private static List<Menu> toTree(Integer id, List<Menu> menus) {
        List<Menu> children = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getParentId().equals(id)){
                List<Menu> children1 =toTree(menu.getId(),menus);
                menu.setChildren(children1);
                children.add(menu);
            }
        }

        return  children;

    }
}
